import { reactive, ref } from 'vue'
import { type PublishProductForm } from '@/types/product'
import type { FormInstance, FormRules, UploadFile } from 'element-plus' // 引入文件类型
import { addProductInfoApi } from '@/api/productInfo'
import { uploadFilesApi } from '@/api/upload'
import { regionData, codeToText } from 'element-china-area-data'
import { useUserStore } from '@/stores'
export default function () {
  const publishFormRef = ref<FormInstance>()
  const addr = ref<string[]>([]) // 用于存储省市区的文本
  // 表单数据
  const publishForm = ref<PublishProductForm>({
    userId: '',
    title: '',
    intro: '',
    image: '',
    price: undefined,
    originalPrice: undefined,
    typeId: '',
    postType: undefined,
    likeCount: 0,
    status: 9,
    adcode: '',
    province: '',
    city: '',
    district: '',
  })

  // 发布商品
  const publish = async (fileList: UploadFile[], formEl: FormInstance | undefined) => {
    // 表单校验
    if (!formEl) return
    await formEl.validate()
    // 表单数据
    publishForm.value.userId = useUserStore().user.id
    try {
      const res = await uploadFilesApi(fileList)
      if (res.code === 0 && res.data.length > 0) {
        // 将数组转换为所需格式的字符串
        publishForm.value.image = `'${res.data.join("','")}'`
        const response = await addProductInfoApi(publishForm.value)
        if (response.code === 0) {
          ElMessage.success('商品发布成功')
          // 刷新页面
          setTimeout(() => {
            window.location.reload()
          }, 1000)
        }
      }
    } catch (error) {
      console.error(error)
      ElMessage.error('商品发布失败')
    }
  }

  // 重置数据
  const reset = () => {
    publishForm.value = {
      userId: '',
      title: '',
      intro: '',
      image: '',
      price: 0,
      originalPrice: 0,
      typeId: '',
      postType: 0,
      likeCount: 0,
      status: 9,
      adcode: '',
      province: '',
      city: '',
      district: '',
    }
  }
  // 监听省市区的变化
  const watchAddr = (value: string[]) => {
    if (value.length === 3) {
      publishForm.value.province = codeToText[value[0]]
      publishForm.value.city = codeToText[value[1]]
      publishForm.value.district = codeToText[value[2]]
      publishForm.value.adcode = value[2]
    }
  }

  // 表单校验规则
  const rules = reactive<FormRules<PublishProductForm>>({
    title: [{ required: true, message: '请输入商品标题', trigger: 'blur' }],
    intro: [{ required: true, message: '请输入商品简介', trigger: 'blur' }],
    image: [{ required: true, message: '请上传商品图片', trigger: 'change' }],
    price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
    originalPrice: [{ required: true, message: '请输入商品原价', trigger: 'blur' }],
    typeId: [{ required: true, message: '请选择商品分类', trigger: 'change' }],
    postType: [{ required: true, message: '请选择发货方式', trigger: 'change' }],
    adcode: [{ required: true, message: '请选择所在地区', trigger: 'change' }],
  })

  return {
    publishFormRef,
    addr,
    publishForm,
    regionData,
    rules,
    publish,
    reset,
    watchAddr,
  }
}
